package com.example.filter;

import com.alibaba.fastjson.JSON;
import com.example.common.BaseContext;
import com.example.util.R;
import lombok.extern.slf4j.Slf4j;
import lombok.extern.slf4j.XSlf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.logging.LogRecord;
//需要在启动类配置@ServletComponentScan
@Slf4j
@WebFilter(filterName = "LoginCheckFilter",urlPatterns = "/*")
public class LoginCheckFilter implements Filter {

    AntPathMatcher antPathMatcher=new AntPathMatcher();

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

        HttpServletRequest request=(HttpServletRequest) servletRequest;
        HttpServletResponse response=(HttpServletResponse) servletResponse;
        String url=request.getRequestURI();
        log.info("拦截到请求{}",url);

        //定义不需要拦截的路径
        String[] urls=new String[]{"/employee/login",
        "/employee/logout",
        "/front/**",
        "/backend/**"};

        if(check(urls,url))
        {
            //
            log.info("不需要处理");
            filterChain.doFilter(request,response);
            return;
        }

        if(request.getSession().getAttribute("employee")!=null)//存的是employee的ID
        {
            log.info("后端");
            //拿到session,把id存入BaseConxt中   //同一线程设置id
            BaseContext.setCurrentId((Long)request.getSession().getAttribute("employee"));   //注意先后顺序
            filterChain.doFilter(request,response);//放行
            return ;
        }
        log.info("用户未登录");
        response.getWriter().write(JSON.toJSONString(R.error("NOTLogin")));  //此处用前端request.js做了校验，如果返回的是NOTLogin则会跳转登陆页面。
//        String basePath = request.getScheme() + "://" + request.getServerName() + ":" +
//                request.getServerPort() +((HttpServletRequest) request).getContextPath()+"/page/login/login.html";//绝对地址
//        System.out.println(basePath);//http://localhost:8080/page/login/login.html
//        // request.getRequestDispatcher(basePath).forward(request,response);
//        response.sendRedirect(basePath);

        return ;
    }

    public boolean check(String[] urls,String url){
        for(String item:urls)
        {
            if(antPathMatcher.match(item,url))
            {
                //匹配一致，放行
                return  true;
            }
        }
        return false;
    }
}
